/*
 * ******************************************************************************
 *   Copyright (c) 2013-2014 Gabriele Mariotti.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *  *****************************************************************************
 */

package it.gmariotti.cardslib.library.view.component;


import it.gmariotti.cardslib.library.AsyncTask;
import it.gmariotti.cardslib.library.Constants;
import it.gmariotti.cardslib.library.ResourceTable;
import it.gmariotti.cardslib.library.internal.CardThumbnail;
import it.gmariotti.cardslib.library.utils.CacheUtil;
import it.gmariotti.cardslib.library.utils.PixelMapUtils;
import it.gmariotti.cardslib.library.view.base.CardViewInterface;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.PixelMapElement;
import ohos.app.Context;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventManager;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.hiviewdfx.HiLog;
import ohos.media.image.PixelMap;
import ohos.rpc.RemoteException;
import ohos.utils.LruBuffer;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.URL;

/**
 * Compound View for Thumbnail Component.
 * </p>
 * It is built with base_thumbnail_layout.xml.
 * </p>
 * Please note that this is currently in a preview state.
 * This means that the API is not fixed and you should expect changes between releases.
 * </p>
 * This class load a bitmap resource using {@link LruBuffer} and using an
 * AsyncTask to prevent UI blocks.
 *
 * @author Gabriele Mariotti (gabri.mariotti@gmail.com)
 */
public class CardThumbnailView extends StackLayout implements CardViewInterface {

    //--------------------------------------------------------------------------
    // Custom Attrs
    //--------------------------------------------------------------------------

    /**
     * Default Layout for Thumbnail View
     */
    protected int card_thumbnail_layout_resourceID = ResourceTable.Layout_base_thumbnail_layout;

    /**
     * Global View for this Component
     */
    protected Component mInternalOuterView;

    /**
     * CardThumbnail model
     */
    protected CardThumbnail mCardThumbnail;

    /**
     * Memory Cache
     */
    protected LruBuffer<String, PixelMap> mMemoryCache;

    /**
     * Used to recycle ui elements.
     */
    protected boolean mIsRecycle = false;

    /**
     * Used to replace inner layout elements.
     */
    protected boolean mForceReplaceInnerLayout = false;


    protected boolean mLoadingErrorResource = false;

    //--------------------------------------------------------------------------
    // Constructors
    //--------------------------------------------------------------------------

    public CardThumbnailView(Context context) {
        super(context);
        init(null, "0");
    }

    public CardThumbnailView(Context context, AttrSet attrs) {
        super(context, attrs);
        init(attrs, "0");
    }

    public CardThumbnailView(Context context, AttrSet attrs, String defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }

    //--------------------------------------------------------------------------
    // View
    //--------------------------------------------------------------------------

    /**
     * ImageView inside CardThumbnail
     */
    protected Image mImageView;

    //--------------------------------------------------------------------------
    // Init
    //--------------------------------------------------------------------------


    /**
     * Initialize
     *
     * @param attrs
     * @param defStyle
     */
    protected void init(AttrSet attrs, String defStyle) {
        //Init attrs
        initAttrs(attrs, defStyle);

        //Init View
        //todo no such method
//      if (!isInEditMode())
        initView();
    }

    /**
     * Init custom attrs.
     *
     * @param attrs
     * @param defStyle
     */
    protected void initAttrs(AttrSet attrs, String defStyle) {

        if (attrs.getAttr("card_thumbnail_layout_resourceID").isPresent()) {
            card_thumbnail_layout_resourceID = attrs.getAttr("card_thumbnail_layout_resourceID").get().getIntegerValue();
        }
    }

    /**
     * Init view
     */
    protected void initView() {

        LayoutScatter inflater = LayoutScatter.getInstance(mContext);
        mInternalOuterView = inflater.parse(card_thumbnail_layout_resourceID, this, true);

        //Get ImageVIew
        mImageView = (Image) findComponentById(ResourceTable.Id_card_thumbnail_image);


        // Get max available VM memory, exceeding this amount will throw an
        // OutOfMemory exception. Stored in kilobytes as LruCache takes an
        // int in its constructor.
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

        // Use 1/8th of the available memory for this memory cache.
        final int cacheSize = maxMemory / 8;

        mMemoryCache = CacheUtil.getMemoryCache();
        if (mMemoryCache == null) {
            mMemoryCache = new LruBuffer<>(cacheSize);
            CacheUtil.putMemoryCache(mMemoryCache);
        }
    }

    //--------------------------------------------------------------------------
    // Add Thumbnail
    //--------------------------------------------------------------------------

    /**
     * Adds a {@link CardThumbnail}.
     * It is important to set all thumbnail values before launch this method.
     *
     * @param cardThumbail thumbnail model
     */
    public void addCardThumbnail(CardThumbnail cardThumbail) {
        mCardThumbnail = cardThumbail;
        buildUI();
    }

    /**
     * Refresh UI
     */
    protected void buildUI() {
        if (mCardThumbnail == null) return;

        if (mIsRecycle)
            mLoadingErrorResource = false;

        //Setup InnerView
        setupInnerView();
    }


    /**
     * Sets the inner view.
     */
    protected void setupInnerView() {

        //Setup Elements before load image
        if (mInternalOuterView != null)
            mCardThumbnail.setupInnerViewElements((ComponentContainer) mInternalOuterView, mImageView);

        //Load bitmap
        if (!mCardThumbnail.isExternalUsage()) {
            if (mCardThumbnail.getCustomSource() != null)
                loadBitmap(mCardThumbnail.getCustomSource(), mImageView);
            else if (mCardThumbnail.getDrawableResource() > 0) {
                loadBitmap(mCardThumbnail.getDrawableResource(), mImageView);
            } else
                loadBitmap(mCardThumbnail.getUrlResource(), mImageView);
        }
    }

    //--------------------------------------------------------------------------
    // Load Bitmap and cache manage
    //--------------------------------------------------------------------------

    public void loadBitmap(int resId, Image imageView) {
        final String imageKey = String.valueOf(resId);
        final PixelMap bitmap = getBitmapFromMemCache(imageKey);

        if (bitmap != null) {
            if (!mCardThumbnail.applyBitmap(imageView, bitmap))
                imageView.setImageElement(new PixelMapElement(bitmap));
            sendBroadcast();
        } else {
            if (cancelPotentialWork(resId, imageView)) {
                final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
                final AsyncDrawable asyncDrawable =
                        new AsyncDrawable(null, task);
                imageView.setImageElement(asyncDrawable);
                task.execute(resId);
            }
        }
    }

    public void loadBitmap(String url, Image imageView) {
        final String imageKey = url;
        final PixelMap bitmap = getBitmapFromMemCache(imageKey);

        if (bitmap != null) {
            if (!mCardThumbnail.applyBitmap(imageView, bitmap))
                imageView.setImageElement(new PixelMapElement(bitmap));
            sendBroadcast();
        } else {
            if (cancelPotentialWork(url, imageView)) {
                final BitmapWorkerUrlTask task = new BitmapWorkerUrlTask(imageView);
                final AsyncDrawableUrl asyncDrawable =
                        new AsyncDrawableUrl(null, task);
                imageView.setImageElement(asyncDrawable);
                task.execute(url);
            }
        }
    }

    public void loadBitmap(CardThumbnail.CustomSource customSource, Image imageView) {
        final String imageKey = customSource.getTag();
        final PixelMap bitmap = getBitmapFromMemCache(imageKey);

        if (bitmap != null) {
            if (!mCardThumbnail.applyBitmap(imageView, bitmap))
                imageView.setImageElement(new PixelMapElement(bitmap));
            sendBroadcast();
        } else {
            if (cancelPotentialWork(customSource, imageView)) {
                final BitmapWorkerCustomSourceTask task = new BitmapWorkerCustomSourceTask(imageView);
                final AsyncDrawableCustomSource asyncDrawable =
                        new AsyncDrawableCustomSource(null, task);
                imageView.setImageElement(asyncDrawable);
                task.execute(customSource);
            }
        }
    }

    protected void addBitmapToMemoryCache(String key, PixelMap bitmap) {
        if (!mLoadingErrorResource && getBitmapFromMemCache(key) == null) {
            if (key != null && bitmap != null) {
                mMemoryCache.put(key, bitmap);
            }
        }
    }

    protected PixelMap getBitmapFromMemCache(String key) {
        if (key == null) return null;
        return mMemoryCache.get(key);
    }


    public static PixelMap decodeSampledBitmapFromResource(ResourceManager resourceManager, int resId,
                                                           int reqWidth, int reqHeight) {
        try {
            Resource resource = resourceManager.getResource(resId);
            return PixelMapUtils.preparePixelmap(resource, reqWidth, reqHeight);
        } catch (Exception e) {
            HiLog.error(Constants.LABEL_LOG, e.toString());
        }

        return null;
    }

    public static PixelMap decodeSampledBitmapFromResource(ResourceManager resourceManager, String resUrl, int reqWidth, int reqHeight) {
        try {
            return PixelMapUtils.preparePixelmap(new URL(resUrl).openStream(), reqWidth, reqHeight);
        } catch (IOException e) {
            HiLog.error(Constants.LABEL_LOG, e.toString());
        }

        return null;
    }


    //--------------------------------------------------------------------------
    // Worker
    //--------------------------------------------------------------------------

    public static boolean cancelPotentialWork(int resId, Image imageView) {
        final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);

        if (bitmapWorkerTask != null) {
            final int bitmapWorkerTaskResId = bitmapWorkerTask.resId;
            if (bitmapWorkerTaskResId != resId) {
                // Cancel previous task
                bitmapWorkerTask.cancel(true);
            } else {
                // The same work is already in progress
                return false;
            }
        }
        // No task associated with the ImageView, or an existing task was cancelled
        return true;
    }

    public static boolean cancelPotentialWork(String url, Image imageView) {
        final BitmapWorkerUrlTask bitmapWorkerTask = getBitmapWorkerUrlTask(imageView);

        if (bitmapWorkerTask != null) {
            final String bitmapWorkerTaskResUrl = bitmapWorkerTask.resUrl;
            if (!bitmapWorkerTaskResUrl.equals(url)) {
                // Cancel previous task
                bitmapWorkerTask.cancel(true);
            } else {
                // The same work is already in progress
                return false;
            }
        }
        // No task associated with the ImageView, or an existing task was cancelled
        return true;
    }

    public static boolean cancelPotentialWork(CardThumbnail.CustomSource customSource, Image imageView) {
        final BitmapWorkerCustomSourceTask bitmapWorkerTask = getBitmapWorkerCustomSourceTask(imageView);

        if (bitmapWorkerTask != null && bitmapWorkerTask.customSource != null) {
            final CardThumbnail.CustomSource bitmapWorkerTaskCustomSource = bitmapWorkerTask.customSource;
            if (bitmapWorkerTaskCustomSource.getTag() != null) {
                if (!bitmapWorkerTaskCustomSource.getTag().equals(customSource.getTag())) {
                    // Cancel previous task
                    bitmapWorkerTask.cancel(true);
                } else {
                    // The same work is already in progress
                    return false;
                }
            }
        }
        // No task associated with the ImageView, or an existing task was cancelled
        return true;
    }

    protected static BitmapWorkerTask getBitmapWorkerTask(Image imageView) {
        if (imageView != null) {
            final Element drawable = imageView.getImageElement();
            if (drawable instanceof AsyncDrawable) {
                final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
                return asyncDrawable.getBitmapWorkerTask();
            }
        }
        return null;
    }

    protected static BitmapWorkerUrlTask getBitmapWorkerUrlTask(Image imageView) {
        if (imageView != null) {
            final Element drawable = imageView.getImageElement();
            if (drawable instanceof AsyncDrawableUrl) {
                final AsyncDrawableUrl asyncDrawable = (AsyncDrawableUrl) drawable;
                return asyncDrawable.getBitmapWorkerUrlTask();
            }
        }
        return null;
    }

    protected static BitmapWorkerCustomSourceTask getBitmapWorkerCustomSourceTask(Image imageView) {
        if (imageView != null) {
            final Element drawable = imageView.getImageElement();
            if (drawable instanceof AsyncDrawableCustomSource) {
                final AsyncDrawableCustomSource asyncDrawable = (AsyncDrawableCustomSource) drawable;
                return asyncDrawable.getBitmapWorkerCustomSourceTask();
            }
        }
        return null;
    }

    class BitmapWorkerTask extends AsyncTask<Integer, Void, PixelMap> {
        private final WeakReference<Image> imageViewReference;
        private int resId = 0;

        public BitmapWorkerTask(Image imageView) {
            // Use a WeakReference to ensure the ImageView can be garbage collected
            imageViewReference = new WeakReference<Image>(imageView);
        }

        // Decode image in background.
        @Override
        protected PixelMap doInBackground(Integer... params) {
            resId = params[0];
            Image thumbnail = imageViewReference.get();
            PixelMap bitmap = decodeSampledBitmapFromResource(getResourceManager(), resId, thumbnail.getWidth(),
                    thumbnail.getHeight());
            if (bitmap != null) {
                addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
                return bitmap;
            } else {
                return null;
            }

        }

        // Once complete, see if ImageView is still around and set bitmap.
        @Override
        protected void onPostExecute(PixelMap bitmap) {
            if (isCancelled()) {
                bitmap = null;
            }

            if (imageViewReference != null && bitmap != null) {
                final Image imageView = imageViewReference.get();
                final BitmapWorkerTask bitmapWorkerTask =
                        getBitmapWorkerTask(imageView);
                if (this == bitmapWorkerTask && imageView != null) {
                    if (!mCardThumbnail.applyBitmap(imageView, bitmap))
                        imageView.setImageElement(new PixelMapElement(bitmap));
                    sendBroadcast();
                    mLoadingErrorResource = false;
                }
            } else {
                sendBroadcast(false);
                if (mCardThumbnail != null && mCardThumbnail.getErrorResourceId() != 0) {
                    if (!mLoadingErrorResource) {
                        //To avoid a loop
                        loadBitmap(mCardThumbnail.getErrorResourceId(), mImageView);
                    }
                    mLoadingErrorResource = true;
                }
            }
        }
    }

    class BitmapWorkerUrlTask extends AsyncTask<String, Void, PixelMap> {
        private final WeakReference<Image> imageViewReference;
        private String resUrl = "";

        public BitmapWorkerUrlTask(Image imageView) {
            // Use a WeakReference to ensure the ImageView can be garbage collected
            imageViewReference = new WeakReference<Image>(imageView);
        }

        // Decode image in background.
        @Override
        protected PixelMap doInBackground(String... params) {
            resUrl = params[0];
            Image thumbnail = imageViewReference.get();
            PixelMap bitmap = decodeSampledBitmapFromResource(getResourceManager(), resUrl, thumbnail.getWidth(),
                    thumbnail.getHeight());
            if (bitmap != null) {
                addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
                return bitmap;
            } else
                return null;
        }

        // Once complete, see if ImageView is still around and set bitmap.
        @Override
        protected void onPostExecute(PixelMap bitmap) {
            if (isCancelled()) {
                bitmap = null;
            }

            if (imageViewReference != null && bitmap != null) {
                final Image imageView = imageViewReference.get();
                final BitmapWorkerUrlTask bitmapWorkerTask =
                        getBitmapWorkerUrlTask(imageView);
                if (this == bitmapWorkerTask && imageView != null) {
                    if (!mCardThumbnail.applyBitmap(imageView, bitmap))
                        imageView.setImageElement(new PixelMapElement(bitmap));
                    sendBroadcast();
                    mLoadingErrorResource = false;
                }
            } else {
                sendBroadcast(false);
                if (mCardThumbnail != null && mCardThumbnail.getErrorResourceId() != 0) {
                    if (!mLoadingErrorResource) {
                        //To avoid a loop
                        loadBitmap(mCardThumbnail.getErrorResourceId(), mImageView);
                    }
                    mLoadingErrorResource = true;
                }
            }
        }
    }

    class BitmapWorkerCustomSourceTask extends AsyncTask<CardThumbnail.CustomSource, Void, PixelMap> {
        private final WeakReference<Image> imageViewReference;
        private CardThumbnail.CustomSource customSource = null;

        public BitmapWorkerCustomSourceTask(Image imageView) {
            // Use a WeakReference to ensure the ImageView can be garbage collected
            imageViewReference = new WeakReference<Image>(imageView);
        }

        // Decode image in background.
        @Override
        protected PixelMap doInBackground(CardThumbnail.CustomSource... params) {
            customSource = params[0];
            Image thumbnail = imageViewReference.get();
            PixelMap bitmap = customSource.getBitmap();
            if (bitmap != null) {
                addBitmapToMemoryCache(customSource.getTag(), bitmap);
                return bitmap;
            } else {
                return null;
            }

        }

        // Once complete, see if ImageView is still around and set bitmap.
        @Override
        protected void onPostExecute(PixelMap bitmap) {
            if (isCancelled()) {
                bitmap = null;
            }

            if (imageViewReference != null && bitmap != null) {
                final Image imageView = imageViewReference.get();
                final BitmapWorkerCustomSourceTask bitmapWorkerTask =
                        getBitmapWorkerCustomSourceTask(imageView);
                if (this == bitmapWorkerTask && imageView != null) {
                    if (!mCardThumbnail.applyBitmap(imageView, bitmap))
                        imageView.setImageElement(new PixelMapElement(bitmap));
                    sendBroadcast();
                    mLoadingErrorResource = false;
                }
            } else {
                sendBroadcast(false);
                if (mCardThumbnail != null && mCardThumbnail.getErrorResourceId() != 0) {
                    if (!mLoadingErrorResource) {
                        //To avoid a loop
                        loadBitmap(mCardThumbnail.getErrorResourceId(), mImageView);
                    }
                    mLoadingErrorResource = true;
                }
            }
        }
    }


    static class AsyncDrawable extends PixelMapElement {
        private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;

        public AsyncDrawable(PixelMap bitmap,
                             BitmapWorkerTask bitmapWorkerTask) {
            super(bitmap);
            bitmapWorkerTaskReference =
                    new WeakReference<BitmapWorkerTask>(bitmapWorkerTask);
        }

        public BitmapWorkerTask getBitmapWorkerTask() {
            return bitmapWorkerTaskReference.get();
        }
    }

    static class AsyncDrawableUrl extends PixelMapElement {
        private final WeakReference<BitmapWorkerUrlTask> bitmapWorkerTaskReference;

        public AsyncDrawableUrl(PixelMap bitmap,
                                BitmapWorkerUrlTask bitmapWorkerTask) {
            super(bitmap);
            bitmapWorkerTaskReference =
                    new WeakReference<BitmapWorkerUrlTask>(bitmapWorkerTask);
        }

        public BitmapWorkerUrlTask getBitmapWorkerUrlTask() {
            return bitmapWorkerTaskReference.get();
        }
    }

    static class AsyncDrawableCustomSource extends PixelMapElement {
        private final WeakReference<BitmapWorkerCustomSourceTask> bitmapWorkerTaskReference;

        public AsyncDrawableCustomSource(PixelMap bitmap,
                                         BitmapWorkerCustomSourceTask bitmapWorkerTask) {
            super(bitmap);
            bitmapWorkerTaskReference =
                    new WeakReference<BitmapWorkerCustomSourceTask>(bitmapWorkerTask);
        }

        public BitmapWorkerCustomSourceTask getBitmapWorkerCustomSourceTask() {
            return bitmapWorkerTaskReference.get();
        }
    }

    //--------------------------------------------------------------------------
    // Broadcast
    //--------------------------------------------------------------------------

    /**
     * Send a successful broadcast when image is downloaded
     */
    protected void sendBroadcast() {
        sendBroadcast(true);
    }

    /**
     * Send a broadcast when image is downloaded
     *
     * @param result
     */
    protected void sendBroadcast(boolean result) {

        if (mCardThumbnail.isSendBroadcastAfterAttach()) {
            Intent intent = new Intent();
            intent.setAction(Constants.IntentManager.INTENT_ACTION_IMAGE_DOWNLOADED);
            intent.setParam(Constants.IntentManager.INTENT_ACTION_IMAGE_DOWNLOADED_EXTRA_RESULT, result);
            if (mLoadingErrorResource)
                intent.setParam(Constants.IntentManager.INTENT_ACTION_IMAGE_DOWNLOADED_EXTRA_ERROR_LOADING, true);
            else
                intent.setParam(Constants.IntentManager.INTENT_ACTION_IMAGE_DOWNLOADED_EXTRA_ERROR_LOADING, false);

            if (mCardThumbnail != null && mCardThumbnail.getParentCard() != null)
                intent.setParam(Constants.IntentManager.INTENT_ACTION_IMAGE_DOWNLOADED_EXTRA_CARD_ID, mCardThumbnail.getParentCard().getId());
            if (getContext() != null) {
                try {
                    CommonEventData commonEventData = new CommonEventData(intent);
                    CommonEventManager.publishCommonEvent(commonEventData);
                } catch (RemoteException e) {
                    HiLog.error(Constants.LABEL_LOG, e.toString());
                }
            }
        }


    }

    //--------------------------------------------------------------------------
    // Getters and Setters
    //--------------------------------------------------------------------------

    @Override
    public Component getInternalOuterView() {
        return null;
    }

    /**
     * Indicates if view can recycle ui elements.
     *
     * @return <code>true</code> if views can recycle ui elements
     */
    public boolean isRecycle() {
        return mIsRecycle;
    }

    /**
     * Sets if view can recycle ui elements
     *
     * @param isRecycle <code>true</code> to recycle
     */
    public void setRecycle(boolean isRecycle) {
        this.mIsRecycle = isRecycle;
    }

    /**
     * Indicates if inner layout have to be replaced
     *
     * @return <code>true</code> if inner layout can be recycled
     */
    public boolean isForceReplaceInnerLayout() {
        return mForceReplaceInnerLayout;
    }

    /**
     * Sets if inner layout have to be replaced
     *
     * @param forceReplaceInnerLayout <code>true</code> to recycle
     */
    public void setForceReplaceInnerLayout(boolean forceReplaceInnerLayout) {
        this.mForceReplaceInnerLayout = forceReplaceInnerLayout;
    }


}
